package com.caiyouxi.boss.buser.controller;

import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.boss.buser.model.SysUserProfileBean;
import com.caiyouxi.boss.buser.service.SysUserProfileService;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.cache.RedisService;
import com.caiyouxi.common.control.BaseController;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.util.MD5Util;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/boss/user")
public class LoginController extends BaseController{

    private Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    SysUserProfileService loginService;
    @Autowired
    RedisService redisService;

    /**
     * 登陆
     * @return
     */
    @RequestMapping("/login")
    public ResData login(HttpServletRequest request, HttpServletResponse response) {
        String at = request.getParameter("at");
        String ip = request.getParameter("ip");
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        JSONObject logs = new JSONObject();
        logs.put("at",at);
        logs.put("ip",ip);
        logs.put("agent", MD5Util.getMACAddress(ip));
        return loginService.login(userName,passWord,logs);
    }

    /**
     * 检查用户登陆状态
     */
    @RequestMapping("/checkStatus")
    public ResData checkUserLoginStatus(HttpServletRequest request, HttpServletResponse response){
        String key = request.getParameter("key");
        SysUserProfileBean bean = (SysUserProfileBean)redisService.get(key);
        if(bean == null){
            return failed(ErrorCode.USER_TIME_OUT.getCode(),ErrorCode.USER_TIME_OUT.getMsg(),null);
        }else {
            //刷新redis
            redisService.set(MD5Util.encryption(bean.getId().toString()+"_"+bean.getUsername()),bean,(long)1600);
            return success(null);
        }
    }

}
